﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;

using MyProFile_V2.Model;
using MyProFile_V2.Data;
using MyProFile_V2.CreateFile;
using VTemplate.Engine;
using Tickz.Commonz;
using Tickz.IOz;

namespace MyProFile_V2.Bll
{
    public class Buildup
    {
        //表对象集合
        private ArrayList tabList = TableService.getTables();
        //保存赋值后的表数据
        private Hashtable tabHash = new Hashtable();
        //项目配置
        private ProInfoModel proInfo = null;

        public ProInfoModel ProInfo
        {
            get { return proInfo; }
            set { proInfo = value; }
        }
        #region 构造方法
        private Buildup() { }
        public Buildup(ProInfoModel proFile)
        {
            this.ProInfo = proFile;
            skipTab();//不生成的表
            fillData();//填充数据
        }
        #endregion

        private void skipTab()
        {//把要不生成的表给skip掉
            string skpTab = proInfo.SkipTable;
            if (string.IsNullOrEmpty(skpTab))
            {
                return;
            }

            foreach (string itme in skpTab.Split(','))
            {
                if (string.IsNullOrEmpty(itme))
                {
                    continue;
                }

                if (tabList.Contains(itme))
                {
                    tabList.Remove(itme);
                }
            }

        }

        #region 初始化数据~
        //把数据填充！
        private void fillData()
        {
            //旧项目路径
            string oldProPath = "";
            //////////////DataAccess////////////////////
            if (proInfo.IsHasOld)
            {
               
            }
            //////////////DataAccess////////////////////
            foreach (TableModel item in tabList)
            {
                if (item.Name == "common_District")
                {
                    string sw = "ss";
                }
                DataModel dataModel = new DataModel();
                //////////////共用////////////////////
                string PK_type = "";
                if (proInfo.IsProFloder)
                {
                    if (proInfo.TabToFloderHas.ContainsKey(item.Name))
                    {
                        dataModel.ParentFloder = proInfo.TabToFloderHas[item.Name].ToString();
                    }
                }

                //////////////共用////////////////////
                //////////////Model////////////////////
                string floderBlowModel = (proInfo.IsProFloder ? (string.IsNullOrEmpty(dataModel.ParentFloder) ? "" : "\\" + dataModel.ParentFloder + "\\") : "");
                string properMoBan = Filez.ReadFileByPath(Directory.GetCurrentDirectory() + "\\Template\\SqlServer\\AbstractFactory\\Entity\\protices.ProTmp");
                string ColumnsProper = "";
               
                //////////////Model////////////////////
                //////////////Bll////////////////////
                string floderBlowBll = (proInfo.IsProFloder ? (string.IsNullOrEmpty(dataModel.ParentFloder) ? "" : "\\" + dataModel.ParentFloder + "\\") : "");
                
                //////////////Bll////////////////////
                //////////////Factory////////////////////
                string floderBlowFactory = (proInfo.IsProFloder ? (string.IsNullOrEmpty(dataModel.ParentFloder) ? "" : "\\" + dataModel.ParentFloder + "\\") : "");
               
                //////////////Factory////////////////////
                //////////////Dal////////////////////
                string floderBlowDal = (proInfo.IsProFloder ? (string.IsNullOrEmpty(dataModel.ParentFloder) ? "" : "\\" + dataModel.ParentFloder + "\\") : "");
                
                string columns = "";
                string columns2 = "";
                string paramsContext = "";
                string PK = "";
                string updateParamsContext = "";
                string updateColumns = "";
                string whereParamsContext = "";
                string whereUpdateColumns = "";
                string selectOneForeachContext = "";
                string selectAllForeachContext = "";
                string selectPagesForeachContext = "";
                string selectAllColumns = "";
                //////////////Dal////////////////////   
                string pkCol = "";
                string firstCol = "";
                int tempNum = 1;
                foreach (ColumnsModel cloum in item.Columns)
                {

                    //////////////共用////////////////////                    
                    if (tempNum == 1)
                    {
                        firstCol = cloum.Name;
                    }
                    tempNum++;
                    if (cloum.IsPK)
                    {
                        PK_type = CurrentProjectFun.getDataType(cloum.Xtype);
                    }
                    if (cloum.Xtype == 58 & cloum.Name.StartsWith("create"))
                    {
                        pkCol = cloum.Name;
                    }
                    //////////////共用////////////////////
                    //////////////Model////////////////////
                    string properTemp = properMoBan;
                    //属性字段
                    properTemp = properTemp.Replace("[Lcolum]", Stringz.ToCamel(cloum.Name)).Replace("[xtype]", CurrentProjectFun.getDataType(cloum.Xtype)).Replace("[Ucolum]", Stringz.ToPascal(cloum.Name)).Replace("[defaultValue]", CurrentProjectFun.getDataDefValue(cloum.Xtype));
                    if (!string.IsNullOrEmpty(cloum.ColDes))
                    {
                        properTemp = properTemp.Replace("[colDes]", cloum.ColDes);
                    }
                    else
                    {
                        properTemp = properTemp.Replace("[colDes]", "该属性暂无描述");
                    }
                    ColumnsProper += properTemp;
                    //////////////Model////////////////////
                    //////////////Bll////////////////////

                    //////////////Bll////////////////////
                    //////////////Factory////////////////////

                    //////////////Factory////////////////////
                    //////////////Dal////////////////////
                    //判断是不是自增列  也不是主键
                    if (!cloum.IsIdentity && !cloum.IsPK)
                    {
                        columns += "["+cloum.Name + "],";
                        columns2 += "@" + cloum.Name + ",";
                        paramsContext +=
                            "new " + CurrentProjectFun.GetParamTypeByDbType(ProInfo.DbType) + "Parameter(\"@" + Stringz.ToCamel(cloum.Name) + "\" ," + Stringz.ToCamel(item.Name) + "." + Stringz.ToPascal(cloum.Name) + "),\r\n\t\t\t\t";
                        updateColumns += "["+cloum.Name + "]=@" + cloum.Name + ",";
                        updateParamsContext += "new " + CurrentProjectFun.GetParamTypeByDbType(ProInfo.DbType) + "Parameter(\"@" + Stringz.ToCamel(cloum.Name) + "\"," + Stringz.ToCamel(item.Name) + "." + Stringz.ToPascal(cloum.Name) + "),\r\n\t\t\t\t";
                    }
                    //判断是不是主键
                    if (cloum.IsPK)
                    {
                        if (cloum.IsIdentity)
                        {
                            PK = cloum.Name;
                            PK_type = CurrentProjectFun.getDataType(cloum.Xtype);
                            whereParamsContext +=
                                "new " + CurrentProjectFun.GetParamTypeByDbType(proInfo.DbType) + "Parameter(\"@" + Stringz.ToCamel(cloum.Name) + "\"," + Stringz.ToCamel(item.Name) + "." + Stringz.ToPascal(cloum.Name) + "),";
                        }else{
                            //主键非自增
                            columns += "["+cloum.Name + "],";
                            columns2 += "@" + cloum.Name + ",";
                            paramsContext +=
                                "new " + CurrentProjectFun.GetParamTypeByDbType(ProInfo.DbType) + "Parameter(\"@" + Stringz.ToCamel(cloum.Name) + "\" ," + Stringz.ToCamel(item.Name) + "." + Stringz.ToPascal(cloum.Name) + "),\r\n\t\t\t\t";
                            updateColumns += "["+cloum.Name + "]=@" + cloum.Name + ",";
                            updateParamsContext += "new " + CurrentProjectFun.GetParamTypeByDbType(ProInfo.DbType) + "Parameter(\"@" + Stringz.ToCamel(cloum.Name) + "\"," + Stringz.ToCamel(item.Name) + "." + Stringz.ToPascal(cloum.Name) + "),\r\n\t\t\t\t";
                        }
                        whereUpdateColumns += "["+cloum.Name + "]=@" + cloum.Name;

                    }
                    if (cloum.Xtype != 34 & cloum.Xtype != 165 & cloum.Xtype != 173 & cloum.Xtype != 62)
                    {
                        selectOneForeachContext += Stringz.ToCamel(item.Name) + "." + Stringz.ToPascal(cloum.Name) + "=Convert.To" + Stringz.ToPascal(CurrentProjectFun.getDataType(cloum.Xtype)) + "(row[\"" + Stringz.ToCamel(cloum.Name) + "\"]);\r\n\t\t\t\t";
                        selectAllForeachContext += Stringz.ToCamel(item.Name) + "." + Stringz.ToPascal(cloum.Name) + "=Convert.To" + Stringz.ToPascal(CurrentProjectFun.getDataType(cloum.Xtype)) + "(row[\"" + Stringz.ToCamel(cloum.Name) + "\"]);\r\n\t\t\t\t";
                        selectPagesForeachContext += Stringz.ToCamel(item.Name) + "." + Stringz.ToPascal(cloum.Name) + "=Convert.To" + Stringz.ToPascal(CurrentProjectFun.getDataType(cloum.Xtype)) + "(row[\"" + Stringz.ToCamel(cloum.Name) + "\"]);\r\n\t\t\t\t";
                    }
                    else if (cloum.Xtype == 62) {
                        selectOneForeachContext += Stringz.ToCamel(item.Name) + "." + Stringz.ToPascal(cloum.Name) + "=(" + Stringz.ToCamel(CurrentProjectFun.getDataType(cloum.Xtype)) + ")(row[\"" + Stringz.ToCamel(cloum.Name) + "\"]);\r\n\t\t\t\t";
                        selectAllForeachContext += Stringz.ToCamel(item.Name) + "." + Stringz.ToPascal(cloum.Name) + "=(" + Stringz.ToCamel(CurrentProjectFun.getDataType(cloum.Xtype)) + ")(row[\"" + Stringz.ToCamel(cloum.Name) + "\"]);\r\n\t\t\t\t";
                        selectPagesForeachContext += Stringz.ToCamel(item.Name) + "." + Stringz.ToPascal(cloum.Name) + "=(" + Stringz.ToCamel(CurrentProjectFun.getDataType(cloum.Xtype)) + ")(row[\"" + Stringz.ToCamel(cloum.Name) + "\"]);\r\n\t\t\t\t";
                    }else
                    {
                        selectOneForeachContext += Stringz.ToCamel(item.Name) + "." + Stringz.ToPascal(cloum.Name) + "=(" + Stringz.ToPascal(CurrentProjectFun.getDataType(cloum.Xtype)) + ")(row[\"" + Stringz.ToCamel(cloum.Name) + "\"]);\r\n\t\t\t\t";
                        selectAllForeachContext += Stringz.ToCamel(item.Name) + "." + Stringz.ToPascal(cloum.Name) + "=(" + Stringz.ToPascal(CurrentProjectFun.getDataType(cloum.Xtype)) + ")(row[\"" + Stringz.ToCamel(cloum.Name) + "\"]);\r\n\t\t\t\t";
                        selectPagesForeachContext += Stringz.ToCamel(item.Name) + "." + Stringz.ToPascal(cloum.Name) + "=(" + Stringz.ToPascal(CurrentProjectFun.getDataType(cloum.Xtype)) + ")(row[\"" + Stringz.ToCamel(cloum.Name) + "\"]);\r\n\t\t\t\t";
                    }
                    selectAllColumns += cloum.Name + ",";
                    //////////////Dal////////////////////   



                }

                //////////////共用////////////////////
                dataModel.PK_type = PK_type;//主键类型
                dataModel.LTableName = Stringz.ToCamel(item.Name);//首字母小写
                dataModel.UTableName = Stringz.ToPascal(item.Name);//首字母大写
                if (string.IsNullOrEmpty(PK))
                {
                    if (string.IsNullOrEmpty(pkCol))
                    {
                        dataModel.PK = firstCol;
                    }
                    else
                    {
                        dataModel.PK = pkCol;
                    }
                }
                else
                {
                    dataModel.PK = PK;
                }
                dataModel.IsView = item.IsView;
                //////////////共用////////////////////
                //////////////Model////////////////////
                dataModel.ColumnsProper = ColumnsProper;//属性模板
                dataModel.TabDes = item.TabDes;
                //////////////Model////////////////////
                //////////////Bll////////////////////

                //////////////Bll////////////////////
                //////////////Factory////////////////////

                //////////////Factory////////////////////
                //////////////Dal////////////////////
                dataModel.Columns = Stringz.DeleteLastStr(columns,1);
                dataModel.Columns2 = Stringz.DeleteLastStr(columns2, 1);
                dataModel.ParamsContext = Stringz.DeleteLastStr(paramsContext, 1);
                dataModel.UpdateColumns = Stringz.DeleteLastStr(updateColumns, 1);
                dataModel.UpdateParamsContext = Stringz.DeleteLastStr(updateParamsContext, 1);
                dataModel.WhereParamsContext = whereParamsContext;
                dataModel.WhereUpdateColumns = whereUpdateColumns;
                dataModel.SelectOneForeachContext = selectOneForeachContext;
                dataModel.SelectAllForeachContext = selectAllForeachContext;
                dataModel.SelectPagesForeachContext = selectPagesForeachContext;
                dataModel.SelectAllColumns = selectAllColumns;
                //////////////Dal////////////////////                 
                tabHash.Add(item.Name, dataModel);
            }
        }
        #endregion        
                
        #region 创建共同的webSite 和 sln
        /// <summary>
        /// 创建共同的webSite 和 sln
        /// </summary>
        public void createCommonSite()
        {

            string ProPathStr = proInfo.ProPath;
            if (Directory.Exists(ProPathStr + "\\webSite"))
            {
                if (!ProInfo.IsHasOld)
                {
                    Directory.Delete(ProPathStr + "\\webSite", true);
                }
            }
         
            //开发工具版本
            string toolV = proInfo.ToolVersion;
            //创建website下的文件夹          
            Directory.CreateDirectory(ProPathStr + "\\webSite\\bin\\Debug");
            Directory.CreateDirectory(ProPathStr + "\\webSite\\obj\\Debug");
            Directory.CreateDirectory(ProPathStr + "\\webSite\\Properties");
            //创建AssemblyInfo.cs
            string AssemblyInfoStr = Filez.ReadFileByPath(Directory.GetCurrentDirectory() + "\\Template\\SqlServer\\AbstractFactory\\Common\\" + toolV + "\\AssemblyInfo.cs");
            AssemblyInfoStr = AssemblyInfoStr.Replace("[Title]", proInfo.ProName);
            AssemblyInfoStr = AssemblyInfoStr.Replace("[Description]", proInfo.ProAuthor);
            AssemblyInfoStr = AssemblyInfoStr.Replace("[Company]", proInfo.CompanyInfo);
            AssemblyInfoStr = AssemblyInfoStr.Replace("[Product]", proInfo.ProName);
            AssemblyInfoStr = AssemblyInfoStr.Replace("[Copyright]", proInfo.CopyRight);
            AssemblyInfoStr = AssemblyInfoStr.Replace("[guid]", Guid.NewGuid().ToString());
            Filez.WriteFileByPath(AssemblyInfoStr, ProPathStr + "\\webSite\\Properties\\AssemblyInfo.cs");           
            //生成webSite层的csproj 文件
            string csprojwebSite = Filez.ReadFileByPath(Directory.GetCurrentDirectory() + "\\Template\\SqlServer\\AbstractFactory\\Common\\" + toolV + "\\webSite.csproj");
            //替换
            csprojwebSite = csprojwebSite.Replace("[proName]", proInfo.ProName);
            csprojwebSite = csprojwebSite.Replace("[DBtype]", proInfo.DbType);
            Filez.WriteFileByPath(csprojwebSite,ProPathStr + "\\webSite\\webSite.csproj");
            //sln文件
            string slnFile = Filez.ReadFileByPath(Directory.GetCurrentDirectory() + "\\Template\\SqlServer\\AbstractFactory\\Common\\" + toolV + "\\proName.sln");
            slnFile = slnFile.Replace("[proName]", proInfo.ProName);
            slnFile = slnFile.Replace("[DBtype]", proInfo.DbType);

            Filez.WriteFileByPath(slnFile.Replace("\r", "").Replace("\n", "\r\n"), ProPathStr + "\\" + proInfo.ProName + ".sln");            

            //web.config文件 
            string webConfigFile = Filez.ReadFileByPath(Directory.GetCurrentDirectory() + "\\Template\\SqlServer\\AbstractFactory\\Common\\" + toolV + "\\Web.config");            
            webConfigFile = webConfigFile.Replace("[dbIp]", proInfo.DbServer);
            webConfigFile = webConfigFile.Replace("[dbName]", proInfo.DbName);
            webConfigFile = webConfigFile.Replace("[uid]", proInfo.DbUid);
            webConfigFile = webConfigFile.Replace("[upass]", proInfo.DbPass);

            webConfigFile = webConfigFile.Replace("[proName]", proInfo.ProName);
            webConfigFile = webConfigFile.Replace("[DBtype]", proInfo.DbType);
            Filez.WriteFileByPath(webConfigFile.Replace("\r", "").Replace("\n", "\r\n"), ProPathStr + "\\webSite\\Web.config");
            //vs2010写入 Web.Debug.config和 Web.Release.config
            if ("vs2010".Equals(toolV))
            {
                string webDebugConfigFile = Filez.ReadFileByPath(Directory.GetCurrentDirectory() + "\\Template\\SqlServer\\AbstractFactory\\Common\\" + toolV + "\\Web.Debug.config");
                Filez.WriteFileByPath(webDebugConfigFile.Replace("\r", "").Replace("\n", "\r\n"), ProPathStr + "\\webSite\\Web.Debug.config");
                string webReleaseConfigFile = Filez.ReadFileByPath(Directory.GetCurrentDirectory() + "\\Template\\SqlServer\\AbstractFactory\\Common\\" + toolV + "\\Web.Release.config");
                Filez.WriteFileByPath(webReleaseConfigFile.Replace("\r", "").Replace("\n", "\r\n"), ProPathStr + "\\webSite\\Web.Release.config");
            }
            //复制tools到bin
            string fromTools = Directory.GetCurrentDirectory() + "\\Template\\SqlServer\\AbstractFactory\\Common\\Tickz.Tools.dll";
            string toTools = ProPathStr + "\\webSite\\bin\\Tickz.Tools.dll";
            File.Copy(fromTools, toTools);

        }
        #endregion
        
        public void setUp()
        {
            //如果存在该key则删除
            if (Template.CommValue.ContainsKey("ProInfo")){
                Template.CommValue.Remove("ProInfo");
            }
            Template.CommValue.Add("ProInfo", proInfo);
            
            CreateEntity.CreateMethod(tabHash,proInfo);
            CreateFactory.CreateMethod(tabHash, proInfo);
            CreateBLL.CreateMethod(tabHash, proInfo);
            CreateSqlServer.CreateMethod(tabHash,proInfo);
            createCommonSite();
        }
    }
}
